// 套餐配置管理模块
const { message, Modal, notification } = window.antd;

// 套餐数据结构
class Package {
    constructor(id, name, description, price, items, allergens = []) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.price = price;
        this.items = items;
        this.allergens = allergens;
    }
}

// 套餐配置管理类
export default class PackageConfigManager {
    constructor() {
        this.packages = [];
        this.selectedPackages = new Set();
    }

    init() {
        // 初始化DOM元素
        this.contentWrapper = document.querySelector('.content-wrapper');
        if (!this.contentWrapper) {
            this.contentWrapper = document.createElement('div');
            this.contentWrapper.className = 'content-wrapper';
            document.querySelector('.main-container').appendChild(this.contentWrapper);
        }

        // 创建套餐列表容器
        this.contentWrapper.innerHTML = `
            <div class="package-config-container">
                <div class="batch-toolbar">
                    <div class="batch-toolbar-info">已选择 0 个套餐</div>
                    <div class="batch-toolbar-actions">
                        <button data-action="delete">批量删除</button>
                        <button data-action="update-price">批量调价</button>
                        <button data-action="update-status">批量更新状态</button>
                    </div>
                </div>
                <div class="package-list-content"></div>
            </div>
        `;

        // 初始化拖拽和事件监听
        this.initDragAndDrop();
        this.initEventListeners();

        // 加载测试数据
        this.loadTestData();
    }

    loadTestData() {
        // 添加一些测试数据
        this.packages = [
            new Package(1, '商务套餐A', '含牛排、沙拉、饮品', 188, ['牛排', '沙拉', '可乐'], ['乳制品']),
            new Package(2, '家庭套餐B', '含披萨、意面、饮品', 258, ['披萨', '意面', '果汁'], ['面筋']),
            new Package(3, '情侣套餐C', '含寿司、刺身、清酒', 298, ['寿司', '刺身', '清酒'], ['海鲜'])
        ];
        this.renderPackageList();
    }

    // 初始化拖拽功能
    initDragAndDrop() {
        const packageList = document.querySelector('.package-list-content');
        if (!packageList) return;

        packageList.addEventListener('dragstart', (e) => {
            const packageCard = e.target.closest('.package-card');
            if (packageCard) {
                packageCard.classList.add('dragging');
                e.dataTransfer.setData('text/plain', packageCard.dataset.id);
            }
        });

        packageList.addEventListener('dragend', (e) => {
            const packageCard = e.target.closest('.package-card');
            if (packageCard) {
                packageCard.classList.remove('dragging');
            }
        });

        packageList.addEventListener('dragover', (e) => {
            e.preventDefault();
            const draggingCard = document.querySelector('.dragging');
            const packageCard = e.target.closest('.package-card');
            if (draggingCard && packageCard && draggingCard !== packageCard) {
                const rect = packageCard.getBoundingClientRect();
                const offset = e.clientY - rect.top - rect.height / 2;
                if (offset < 0) {
                    packageCard.parentNode.insertBefore(draggingCard, packageCard);
                } else {
                    packageCard.parentNode.insertBefore(draggingCard, packageCard.nextSibling);
                }
            }
        });
    }

    // 初始化事件监听
    initEventListeners() {
        // 批量选择事件
        document.addEventListener('change', (e) => {
            if (e.target.matches('.package-select')) {
                const packageId = e.target.closest('.package-card').dataset.id;
                if (e.target.checked) {
                    this.selectedPackages.add(packageId);
                } else {
                    this.selectedPackages.delete(packageId);
                }
                this.updateBatchToolbar();
            }
        });

        // 批量操作事件
        const batchActions = document.querySelector('.batch-toolbar-actions');
        if (batchActions) {
            batchActions.addEventListener('click', (e) => {
                const action = e.target.dataset.action;
                if (action) {
                    this.handleBatchAction(action);
                }
            });
        }
    }

    // 更新批量操作工具栏
    updateBatchToolbar() {
        const info = document.querySelector('.batch-toolbar-info');
        if (info) {
            info.textContent = `已选择 ${this.selectedPackages.size} 个套餐`;
        }
    }

    // 处理批量操作
    handleBatchAction(action) {
        if (this.selectedPackages.size === 0) {
            message.warning('请先选择要操作的套餐');
            return;
        }

        switch (action) {
            case 'delete':
                this.batchDelete();
                break;
            case 'update-price':
                this.batchUpdatePrice();
                break;
            case 'update-status':
                this.batchUpdateStatus();
                break;
        }
    }

    // 批量删除
    batchDelete() {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${this.selectedPackages.size} 个套餐吗？`,
            onOk: () => {
                // 执行删除操作
                this.selectedPackages.forEach(id => {
                    const index = this.packages.findIndex(p => p.id === id);
                    if (index !== -1) {
                        this.packages.splice(index, 1);
                    }
                });
                this.selectedPackages.clear();
                this.updateBatchToolbar();
                this.renderPackageList();
                message.success('删除成功');
            }
        });
    }

    // 批量更新价格
    batchUpdatePrice() {
        Modal.confirm({
            title: '批量调整价格',
            content: '请输入调整比例（%）',
            onOk: (value) => {
                const percent = parseFloat(value);
                if (isNaN(percent)) {
                    message.error('请输入有效的数字');
                    return;
                }

                this.selectedPackages.forEach(id => {
                    const pkg = this.packages.find(p => p.id === id);
                    if (pkg) {
                        pkg.price *= (1 + percent / 100);
                    }
                });

                this.renderPackageList();
                message.success('价格调整成功');
            }
        });
    }

    // 批量更新状态
    batchUpdateStatus() {
        Modal.confirm({
            title: '批量更新状态',
            content: '请选择要更新的状态',
            onOk: (status) => {
                this.selectedPackages.forEach(id => {
                    const pkg = this.packages.find(p => p.id === id);
                    if (pkg) {
                        pkg.status = status;
                    }
                });

                this.renderPackageList();
                message.success('状态更新成功');
            }
        });
    }

    // 渲染套餐卡片
    renderPackageCard(pkg) {
        return `
            <div class="package-card draggable-item" draggable="true" data-id="${pkg.id}">
                <input type="checkbox" class="package-select" ${this.selectedPackages.has(pkg.id) ? 'checked' : ''}>
                <div class="package-card-info">
                    <h3 class="package-card-title">${pkg.name}</h3>
                    <p class="package-card-description">${pkg.description}</p>
                    <div class="package-items">
                        <strong>包含项目：</strong>${pkg.items.join('、')}
                    </div>
                    <div class="package-allergens">
                        <strong>过敏原：</strong>${pkg.allergens.join('、')}
                    </div>
                    <div class="package-card-price">¥${pkg.price.toFixed(2)}</div>
                </div>
                <div class="package-card-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            </div>
        `;
    }

    // 渲染过敏原标签
    renderAllergenTags(allergens) {
        if (!allergens || allergens.length === 0) return '';
        
        return `
            <div class="allergen-tags">
                ${allergens.map(allergen => `
                    <span class="allergen-tag">${allergen}</span>
                `).join('')}
            </div>
        `;
    }

    // 渲染套餐列表
    renderPackageList() {
        const packageListContent = document.querySelector('.package-list-content');
        if (!packageListContent) return;

        packageListContent.innerHTML = this.packages.map(pkg => this.renderPackageCard(pkg)).join('');
    }

    // 渲染套餐卡片
    renderPackageCard(pkg) {
        return `
            <div class="package-card" data-id="${pkg.id}" draggable="true">
                <input type="checkbox" class="package-select" ${this.selectedPackages.has(pkg.id) ? 'checked' : ''}>
                <div class="package-card-info">
                    <h3 class="package-card-title">${pkg.name}</h3>
                    <p class="package-card-description">${pkg.description}</p>
                    <div class="package-card-items">
                        ${pkg.items.map(item => `<span class="package-item">${item}</span>`).join('')}
                    </div>
                    ${this.renderAllergenTags(pkg.allergens)}
                    <div class="package-card-price">¥${pkg.price.toFixed(2)}</div>
                </div>
                <div class="package-card-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            </div>
        `;
    }
}

// 导出套餐配置管理实例
export const packageConfigManager = new PackageConfigManager();